import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Popconfirm, Popover, Modal, InputNumber, List } from 'antd';
import usePageAccess from '@/components/usePageAccess';
import { Access, history } from '@umijs/max'
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryMoneyCardTemplateListParams, MoneyCardTemplate } from './services';
import { 
  queryMoneyCardTemplateList, delMoneyCardTemplate, makeCardBatch, getStationsById,
} from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import Ellipsis from '@/components/Ellipsis';
import dayjs from 'dayjs';
import CardListModal, { CardListModalProps } from './components/CardListModal';
import { EyeOutlined } from '@ant-design/icons';
import { jump2target } from '@/utils/common';

const MoneyCardTemplatePage: React.FC = () => {
  const access = usePageAccess()
  const [makeCardForm] = Form.useForm()
  const [searchForm] = Form.useForm<QueryMoneyCardTemplateListParams>()
  const [searchParams, setSearchParams] = useState<QueryMoneyCardTemplateListParams>({
    pageNum: 1, pageSize: 10,
  })
  const moneyCardList = useRequest(() => queryMoneyCardTemplateList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: delMoneyCardTemplateAsync } = useRequest(delMoneyCardTemplate, {manual: true})
  const { runAsync: makeCardBatchAsync, loading: makeCardBatchLoading } = useRequest(makeCardBatch, {manual: true})
  const { runAsync: getStations } = useRequest(getStationsById, {manual: true})
  const [makeCardRecord, setMakeCardRecord] = useState<MoneyCardTemplate>()
  const [cardListModalProps, setCardListModalProps] = useState<CardListModalProps>()

  const openEditPage = (title: string, type: string, couponId?: number) => {
    jump2target(`/coupon/cardList/edit?type=${type}&id=${couponId || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/coupon/cardList/edit_title', title)
  }

  const onFinish = (formValues: QueryMoneyCardTemplateListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const openMakeCardModal = (record: MoneyCardTemplate) => {
    setMakeCardRecord(record)
  }

  const onMakeCardModalCancel = () => {
    makeCardForm.resetFields()
    setMakeCardRecord(undefined)
  }

  const onMakeCardModalOk = () => {
    makeCardForm.validateFields()
    .then((values: any) => {
      makeCardBatchAsync({
        id: makeCardRecord!.id,
        num: values.num,
      }).then(() => {
        moneyCardList.refresh()
        onMakeCardModalCancel()
      })
    })
  }

  const openMakeCardListModal = (record: MoneyCardTemplate) => {
    setCardListModalProps({
      infoId: record.id,
    })
  }

  const onCardListModalCancel = () => {
    setCardListModalProps(undefined)
  }

  const showAllStation = (id: MoneyCardTemplate['id']) => {
    getStations({infoId: id, pageSize: 100, pageNum: 1}).then(res => {
      Modal.info({
        title: '适用场站',
        content: <List
          dataSource={res.data}
          renderItem={item => <List.Item>{item.stationName}</List.Item>}
        />
      })
    })
  }

  const columns: ColumnsType<MoneyCardTemplate> = [
    {
      title: '现金卡ID',
      dataIndex: 'id',
      width: 120,
    },
    {
      title: '现金卡名称',
      dataIndex: 'title',
      width: 120,
    },
    {
      title: '面额(元)',
      dataIndex: 'totalM',
      width: 100,
    },
    {
      title: '制卡数量(张)',
      dataIndex: 'totalNum',
      width: 120,
    },
    {
      title: '有效天数(天)',
      dataIndex: 'expireDay',
      width: 120,
      render: val => val ? `${val}天` : '永久有效'
    },
    {
      title: '适用范围',
      dataIndex: 'stationType',
      width: 140,
      render: (val, record) => {
        if (val === 2) {
          return <a onClick={() => showAllStation(record.id)}>部分场站 <EyeOutlined /></a>
        }
        return '全部自营场站'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
      render: val => val && dayjs(val).format('YYYY-MM-DD')
    },
    {
      title: '描述',
      dataIndex: 'commend',
      width: 200,
      render: val => {
        return <Popover content={val} placement='topLeft'>
          <Ellipsis>{val || '--'}</Ellipsis>
        </Popover>
      }
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 160,
      fixed: 'right',
      render: (id: number, record) => {
        return <Space>
          <a onClick={() => openMakeCardListModal(record)}>卡列表</a>
          <a onClick={() => openMakeCardModal(record)}>制卡</a>
          <Popconfirm
            title={`确定删除现金卡: ${record.title} 吗?`}
            onConfirm={() => delMoneyCardTemplateAsync({id: record.id}).then(moneyCardList.refresh)}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      }
    }
  ]

  useEffect(() => {
    const refresh = () => {
      moneyCardList.refresh()
    }
    window.addEventListener('refreshMoneyCardTemplateList', refresh)
    return () => {
      window.removeEventListener('refreshMoneyCardTemplateList', refresh)
    }
  }, [])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <Access accessible={!!access.add || true}>
          <div className="toolbar">
            <Space>
              <Button type='primary' onClick={() => openEditPage('添加现金卡', 'edit')}>添加现金卡</Button>
            </Space>
          </div>
        </Access>
        <div className="form-area">
          <Form name='searchMoneyCardForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='现金卡名称' name='title'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={moneyCardList.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<MoneyCardTemplate>
          rowKey='id'
          loading={moneyCardList.loading}
          dataSource={moneyCardList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: moneyCardList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <Modal
        open={!!makeCardRecord}
        title='批量制卡'
        width={400}
        onCancel={onMakeCardModalCancel}
        onOk={onMakeCardModalOk}
        confirmLoading={makeCardBatchLoading}
      >
        <Form form={makeCardForm} name='makeCardForm' labelCol={{span: 6}}>
          <Form.Item label='卡模板'>{makeCardRecord?.title}</Form.Item>
          <Form.Item label='数量' name='num' rules={[{required: true, message: '请输入制卡数量'}]}>
            <InputNumber placeholder='请输入' style={{width: '100%'}} min={1} max={100} precision={0} />
          </Form.Item>
        </Form>
      </Modal>
      <CardListModal
        {...cardListModalProps}
        onCancel={onCardListModalCancel}
      />
    </div>
  );
};

export default MoneyCardTemplatePage;
